import re
import os

file_dir = "server/sql/files/"
route = "download_file"


def get_file_path(url, alink):
    """返回文件地址和超链接"""
    global file_dir
    url = url.replace("\\", "/")
    num = len(os.listdir(file_dir))
    path = re.findall(r'<a href=([\s\S]*)><img src=', alink)[0]
    exts = os.path.basename(path).split('.')
    if exts:
        ext = "."+exts[-1]
    else:
        ext = ""
    file_path = os.path.join(file_dir, str(num)+ext)
    text = re.sub(r'<a href=([\s\S]*)><img src=', "<a href="+url + route + "?file"+str(num)+"><img src=", alink)
    return file_path, text


def copy_img(uid, mode):
    """复制一个默认头像"""
    img_dir = "server/sql/img_buf/"
    if mode == "friend":
        default_path = "user_default.png"
        img_path = "u"+str(uid)+".png"
    else:
        default_path = "group_default.png"
        img_path = "g"+str(uid)+".png"
    img = open(img_dir+default_path, "rb").read()
    with open(img_dir+img_path, "wb") as f:
        f.write(img)
